package com.gec.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.system.exception.MyCustomException;
import com.gec.system.mapper.SysMenuMapper;
import com.gec.system.system.SysMenu;
import com.gec.system.service.SysMenuService;
import com.gec.system.utils.MenuHelper;
import com.gec.system.utils.RouterHelper;
import com.gec.system.vo.RouterVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 18236
 * @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
 * @createDate 2024-09-23 09:20:28
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService{

    @Override
    public List<SysMenu> findNode() {
        List<SysMenu> menus = baseMapper.selectList(null);
        menus = MenuHelper.bulidTree(menus);

        return  menus;
    }

    @Override
    public boolean removeMenuById(Long id) {
        boolean isOk=true;
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Long i = Long.valueOf(baseMapper.selectCount(wrapper));
        if(i>0){
            isOk=false;
            throw  new MyCustomException(201,"请删除子菜单");
        }
        baseMapper.deleteById(id);
        return isOk;

    }

    @Override
    public boolean updateStauts(SysMenu menu) {
        return this.baseMapper.updateStatusInteger(menu);
    }

    @Override
    public List<RouterVo> findUserMenuList(Long id) {
        List<SysMenu> sysMenuList= null;
        if (id ==1){
            sysMenuList = baseMapper.selectList(new QueryWrapper<SysMenu>().eq("status", 1).orderByAsc("sort_value"));

        }else {
            sysMenuList=baseMapper.findMenuListByUserId(id);
        }
        List<SysMenu> sysMenuTreeList = MenuHelper.bulidTree(sysMenuList);
        //TODO  MeunHelper返回的数据属性和 前端路由的属性不一致，所以要处理
        //d.构建路由
        return RouterHelper.buildRouters(sysMenuTreeList);
    }

    @Override
    public List<String> findUserPermsList(Long id) {
        List<SysMenu> sysMenusList =null;
        if (id ==1){
            sysMenusList=baseMapper.selectList(new QueryWrapper<SysMenu>().eq("status",1));

        }else {
            sysMenusList= baseMapper.findMenuListByUserId(id);
        }
        ArrayList<String> permissionList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenusList) {
            if (sysMenu.getType()==2){
                permissionList.add(sysMenu.getPerms());
            }
        }
        return permissionList;
    }


}




